<?php
/**
 * 
 * Pages module
 * 
 * @name			Pages
 * @description		Standard pages module for Cosa admin
 * @version			1.0.0
 * 
 * @author			Stijn Van Minnebruggen
 * @author_url		www.donotfold.be
 * @module_url		www.donotfold.be/projects/cosa
 * 
 * @sub1			pages
 * @sub2			navigations
 * @sub3			versions
 * 
 */

class pages extends Module
{
	
	/**
	 * Install script for module
	 * 
	 * @return	bool
	 */
	
	public function install($die=false)
	{
		// required
			global $cosa, $db;
		
		// create pages table
			$sql = "CREATE TABLE IF NOT EXISTS `".$db->module('pages')."` (
					`id` int(11) NOT NULL auto_increment,
					`name` varchar(255) NOT NULL,
					`language_id` int(11) NOT NULL,
					`skin_id` int(11) NOT NULL,
					`title` varchar(255) NOT NULL,
					`text` text NOT NULL,
					`meta_title` varchar(255) NOT NULL,
					`meta_keywords` varchar(255) NOT NULL,
					`meta_description` varchar(255) NOT NULL,
					`original_id` int(11) NOT NULL,
					`published` enum('0','1') NOT NULL default '0',
					`created_by` int(11) NOT NULL,
					`time_created` datetime NOT NULL,
					PRIMARY KEY  (`id`)
					) ENGINE=MyISAM;
					";
			if(!@mysql_query($sql)) {
				if($die) $cosa->oops('Could not install pages module (1).', 'db');
				else return false;
			}
		
		// create navigations table
			$sql = "CREATE TABLE IF NOT EXISTS `".$db->module('pages_nav')."` (
					`id` int(11) NOT NULL auto_increment,
					`language_id` int(11) NOT NULL,
					`title` varchar(255) NOT NULL,
					`type` enum('int','ext','nav') NOT NULL default 'int',
					`page_id` int(11) NOT NULL,
					`ext_url` varchar(255) NOT NULL,
					`ext_target` varchar(255) NOT NULL,
					`parent_id` int(11) NOT NULL default '0',
					`weight` int(11) NOT NULL,
					PRIMARY KEY  (`id`)
					) ENGINE=MyISAM
					";
			if(!@mysql_query($sql)) {
				if($die) $cosa->oops('Could not install pages module (2).', 'db');
				else return false;
			}
		
		// create skins table
			$sql = "CREATE TABLE IF NOT EXISTS `".$db->module('pages_skins')."` (
					`id` int(11) NOT NULL auto_increment,
					`name` varchar(255) NOT NULL,
					`active` enum('1','0') NOT NULL default '1',
					PRIMARY KEY  (`id`)
					) ENGINE=MyISAM
					";
			if(!@mysql_query($sql)) {
				if($die) $cosa->oops('Could not install pages module (3).', 'db');
				else return false;
			}
		
		// insert default skin
			$sql = "INSERT INTO `".$db->module('pages_skins')."` SET name = 'Default'";
			if(!@mysql_query($sql)) {
				if($die) $cosa->oops('Could not install pages module (4).', 'db');
				else return false;
			}
		
		// return success
			return true;
		
	}
	
	
	/**
	 * Uninstall script for module
	 * 
	 * @return	bool
	 */
	
	public function uninstall()
	{
		global $cosa;
		$sql = "DROP TABLE `".$db->module('pages')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall pages module (1).', 'db');
		$sql = "DROP TABLE `".$db->module('pages_nav')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall pages module (2).', 'db');
		$sql = "DROP TABLE `".$db->module('pages_skins')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall pages module (3).', 'db');
		return true;
	}
	
	
	/**
	 * Publish a page
	 * 
	 * @param	int			$page_id
	 * @return	bool
	 */
	
	public function publishPage($page_id)
	{
		// required
			global $cosa, $db;
		
		// get original page id
			$sql = "SELECT original_id FROM ".$db->module('pages')." WHERE id = '".addslashes($page_id)."'";
			$res = mysql_query($res) or $cosa->oops('Could not publish page (1).', 'db');
			$row = mysql_fetch_array($res);
			if(!mysql_num_rows($res)) $cosa->oops('Could not publish page (2).');
			$oid = stripslashes($row['original_id']);
		
		// unpublish all pages
			$sql = "UPDATE ".$db->module('pages')." SET publish = '0' WHERE original_id = '".addslashes($oid)."'";
			mysql_query($sql) or $cosa->oops('Could not publish page (2).', 'db');
		
		// publish new page
			$sql = "UPDATE ".$db->module('pages')." SET publish = '1' WHERE id = '".addslashes($page_id)."'";
			mysql_query($sql) or $cosa->oops('Could not publish page (3).', 'db');
			return true;
		
	}
	
	
	/**
	 * Add a page
	 * 
	 * @param	array	$postVars
	 * @return	bool
	 */
	
	public function pages_add($postVars)
	{
		// required
			global $cosa, $db, $user, $modules, $lang, $path;
			if(!isset($postVars) || empty($postVars)) {
				$modules->addMessage($lang->get('add-page-failed'));
				return false;
			}
		
		// add page
			$sql = "INSERT INTO ".$db->module('pages')."
					SET	name				= '".addslashes($postVars['name'])."'
						,language_id		= '".$lang->id."'
						,skin_id			= '".addslashes($postVars['skin_id'])."'
						,title				= '".addslashes($postVars['title'])."'
						,text				= '".addslashes($postVars['text'])."'
						,meta_title			= '".addslashes($postVars['text'])."'
						,meta_keywords		= '".addslashes($postVars['text'])."'
						,meta_description	= '".addslashes($postVars['text'])."'
						,origial_id			= '".addslashes($postVars['origial_id'])."'
						,published			= '0'
						,created_by			= '".addslashes($user->id())."'
						,time_created		= NOW()
					";
			@mysql_query($sql) or $cosa->kill($lang->get('add-page-failed'), 'db');
			$page_id = mysql_insert_id();
		
		// set nav vars
			$nav = array('title'		=> addslashes($postVars['nav_title'])
						,'type'			=> 'int'
						,'page_id'		=> $page_id
						,'ext_url'		=> ''
						,'ext_target'	=> ''
						,'parent_id'	=> addslashes($postVars['nav_parent_id'])
						,'weight'		=> addslashes($postVars['nav_weight'])
						);
			if(!empty($postVars['nav_title'])) $this->navigations_add($nav);
		
		// save path
			$path->create($postVars['title'], $db->module('pages'), $lang->id, $page_id);
		
		// return success
			$modules->addMessage($lang->get('add-page-success'));
			return true;
		
	}
	
	
	/**
	 * Edit a page
	 * 
	 * @param	array	$postVars
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function pages_edit($postVars, $id)
	{
		/*
		// required
			global $cosa, $db, $user, $modules, $lang, $path;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('edit-page-failed'));
				return false;
			}
		
		// edit page
			$sql = "UPDATE ".$db->module('pages')."
					SET	title			= '".addslashes($postVars['title'])."'
						,text			= '".addslashes($postVars['text'])."'
						,created_by		= '".addslashes($user->id())."'
					WHERE
						id				= '".addslashes($postVars['edit'])."'
					";
			@mysql_query($sql) or $cosa->kill($lang->get('edit-page-failed'), 'db');
		
		// set nav vars
			$nav = array('title'		=> addslashes($postVars['nav_title'])
						,'type'			=> 'int'
						,'page_id'		=> addslashes($postVars['edit'])
						,'ext_url'		=> ''
						,'ext_target'	=> ''
						,'parent_id'	=> addslashes($postVars['nav_parent_id'])
						,'weight'		=> addslashes($postVars['nav_weight'])
						);
		
		// add or edit navigation
			if(isset($postVars['nid'])) {
				if(empty($postVars['nav_title'])) {
					$this->navigations_del($postVars['nid']);
				} else {
					$nav['edit'] = addslashes($postVars['nid']);
					$this->navigations_edit($nav, addslashes($postVars['nid']));
				}
			} else if(!empty($postVars['nav_title'])) {
				$this->navigations_add($nav);
			}
		
		// save path
			$path->create($postVars['title'], $db->module('pages'), $lang->id, $postVars['edit']);
		
		// return success
			$modules->addMessage($lang->get('edit-page-success'));
			return true;
		*/
	}
	
	
	/**
	 * Delete a page
	 * 
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function pages_del($id)
	{
		/*
		// required
			global $cosa, $db, $modules, $lang, $path;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('del-page-failed'));
				return false;
			}
		
		// delete page
			$sql = "DELETE FROM ".$db->module('pages')." WHERE id ='".addslashes($id)."' LIMIT 1";
			@mysql_query($sql) or $cosa->kill($lang->get('del-page-failed'), 'db');
		
		// delete all navigation items related to this page
			$sql = "DELETE FROM ".$db->module('pages_nav')." WHERE type='int' AND page_id = '".$id."'";
			@mysql_query($sql) or $cosa->kill($lang->get('del-nav-failed'), 'db');
		
		// delete path
			$path->delete($db->module('pages'), $id);
		
		// add message to pool
			$modules->addMessage($lang->get('del-page-success'));
			return true;
		*/
	}
	
	
	/**
	 * Get one page
	 * 
	 * @param	int		$id
	 * @return	array
	 */
	
	public function pages_get($id)
	{
		// required
			global $cosa, $db;
			if(!isset($id) || empty($id)) return false;
		
		// execute query
			$sql = "SELECT * FROM ".$db->module('pages')." WHERE id ='".addslashes($id)."' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch item.', 'db');
		
		// return result
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Add a navigation
	 * 
	 * @param	array	$postVars
	 * @return	bool
	 */
	
	public function navigations_add($postVars)
	{
		// required
			global $cosa, $db, $user, $modules, $lang;
			if(!isset($postVars) || empty($postVars)) {
				$modules->addMessage($lang->get('add-navigation-failed'));
				return false;
			}
		
		// create query
			$sql = "INSERT INTO ".$db->module('pages_nav')."
					SET	language_id		= '".addslashes($lang->id)."'
						,title			= '".addslashes($postVars['title'])."'
						,type			= '".addslashes($postVars['type'])."'
						,page_id		= '".addslashes($postVars['page_id'])."'
						,ext_url		= '".addslashes($postVars['ext_url'])."'
						,ext_target		= '".addslashes($postVars['ext_target'])."'
						,parent_id		= '".addslashes($postVars['parent_id'])."'
						,weight			= '".addslashes($postVars['weight'])."'
					";
		
		// execute query
			@mysql_query($sql) or $cosa->kill($lang->get('add-navigation-failed'), 'db');
			$modules->addMessage($lang->get('add-navigation-success'));
			return true;
		
	}
	
	
	/**
	 * Edit a navigation
	 * 
	 * @param	array	$postVars
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function navigations_edit($postVars, $id)
	{
		// required
			global $cosa, $db, $user, $modules, $lang;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('edit-navigation-failed'));
				return false;
			}
		
		// create query
			$sql = "UPDATE ".$db->module('pages_nav')."
					SET	title			= '".addslashes($postVars['title'])."'
						,type			= '".addslashes($postVars['type'])."'
						,page_id		= '".addslashes($postVars['page_id'])."'
						,ext_url		= '".addslashes($postVars['ext_url'])."'
						,ext_target		= '".addslashes($postVars['ext_target'])."'
						,parent_id		= '".addslashes($postVars['parent_id'])."'
						,weight			= '".addslashes($postVars['weight'])."'
					WHERE
						id				= '".addslashes($postVars['edit'])."'
					";
		
		// execute query
			@mysql_query($sql) or $cosa->kill($lang->get('edit-navigation-failed'), 'db');
			$modules->addMessage($lang->get('edit-navigation-success'));
			return true;
		
	}
	
	
	/**
	 * Delete a navigation
	 * 
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function navigations_del($id)
	{
		// required
			global $cosa, $db, $modules, $lang;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('del-navigation-failed'));
				return false;
			}
		
		// execute query
			$sql = "DELETE FROM ".$db->module('pages_nav')." WHERE id ='".addslashes($id)."' LIMIT 1";
			@mysql_query($sql) or $cosa->kill($lang->get('del-navigation-failed'), 'db');
		
		// update children
			$sql = "UPDATE ".$db->module('pages_nav')." SET parent_id = '0' WHERE parent_id='".addslashes($id)."'";
			@mysql_query($sql) or $cosa->kill($lang->get('del-navigation-failed'), 'db');
		
		// add message to pool
			$modules->addMessage($lang->get('del-navigation-success'));
			return true;
		
	}
	
	
	/**
	 * Get one navigation
	 * 
	 * @param	int		$id
	 * @return	array
	 */
	
	public function navigations_get($id)
	{
		// required
			global $cosa, $db;
			if(!isset($id) || empty($id)) return false;
		
		// execute query
			$sql = "SELECT * FROM ".$db->module('pages_nav')." WHERE id ='".addslashes($id)."' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch item.', 'db');
		
		// return result
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Print navigation dropdown
	 * 
	 * @param	string	$name
	 * @param	int		$selected_id
	 * @param	int		$excludeId
	 * @return	void
	 */
	
	public function printNavDropdown($name, $selected_id=false, $excludeId=false)
	{
		// required
			global $cosa, $db, $lang;
			$this->_dashChar = '&mdash;';
						$this->_dashes = 1;
		
		// start select
			echo '<select name="'.$name.'">'."\n";
			echo "\t".'<option value="">'.$lang->get('nav-none').'</option>'."\n";
		
		// print navigation children
			$this->_printNavChildren(0, $selected_id, $excludeId);
		
		// close select
			echo '</select>'."\n";
		
	}
	
	
	/**
	 * Print navigation children for dropdown (recursive function)
	 * 
	 * @param	int		$parent_id
	 * @param	int		$selected_id
	 * @param	int		$includeOwnID
	 * @return	void
	 */
	
	private function _printNavChildren($parent_id, $selected_id=false, $excludeId=false)
	{
		// fetch children
			global $cosa, $db, $lang;
			$sql = "SELECT id, title FROM ".$db->module('pages_nav')." WHERE parent_id = '".$parent_id."' AND language_id='".$lang->id."' ORDER BY weight";
			$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch pages.');
		
		// no results, stop recursive loop
			if(!mysql_num_rows($res)) return false;
			else $this->_dashes++;
		
		// reset dashes
			if($parent_id == 0) $this->_dashes = 0;
		
		// print children
			while($row = mysql_fetch_array($res)) {
				
				if(!$excludeId || ($excludeId && $row['id'] != $excludeId)) {
					
					// print row
						$selected = ($selected_id == $row['id']) ? ' selected="selected"' : '';
						echo '<option value="'.$row["id"].'"'.$selected.'>';
						for($i=0; $i<$this->_dashes; $i++) echo $this->_dashChar;
						echo ' '.stripslashes($row['title']);
						echo '</option>'."\n";
					
					// print children
						$this->_printNavChildren($row['id'], $selected_id, $excludeId);
					
				}
				
			}
		
		// remove one dash
			if($this->_dashes > 0) $this->_dashes--;
		
	}
	
	
	/**
	 * Check if navigation has children
	 * 
	 * @param	int		$nav_id
	 * @return	bool
	 */
	
	public function navHasChildren($nav_id)
	{
		global $cosa, $db;
		$sql = "SELECT id FROM ".$db->module('pages_nav')." WHERE parent_id = '".$nav_id."' LIMIT 1";
		$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch children.');
		return (mysql_num_rows($res)) ? true : false;
	}
	
	
	/**
	 * Get navigation from page id
	 * 
	 * @param	int		$page_id
	 * @return	array
	 */
	
	public function getNavFromPageId($page_id)
	{
		// fetch page
			global $cosa, $db, $lang;
			$sql = "SELECT id, title, weight, parent_id FROM ".$db->module('pages_nav')." WHERE page_id = '".$page_id."' AND language_id='".$lang->id."' LIMIT 1";
			$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch navigation.');
		
		// return data
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Print pages dropdown
	 * 
	 * @param	string	$name
	 * @param	int		$selected_id
	 * @return	void
	 */
	
	public function printPagesDropdown($name, $selected_id=false)
	{
		// required
			global $cosa, $db, $lang;
		
		// start select
			echo '<select name="'.$name.'">'."\n";
			echo "\t".'<option value="">'.$lang->get('nav-none').'</option>'."\n";
		
		// first, fetch pages without navigation
			$sql = "SELECT id, title FROM ".$db->module('pages')." WHERE language_id='".$lang->id."' ORDER BY title";
			$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch pages.');
			while($row = mysql_fetch_array($res)) {
				
				// print row
					$selected = ($selected_id == $row['id']) ? ' selected="selected"' : '';
					echo '<option value="'.$row["id"].'"'.$selected.'>';
					echo stripslashes($row["title"]);
					echo '</option>'."\n";
				
			}
		
		// close select
			echo '</select>'."\n";
		
	}
	
	
	/**
	 * Get page skins
	 * 
	 * @param	bool		$active
	 * @return	array
	 */
	
	public function getSkins($active=true)
	{
		// required
			global $cosa, $db;
			$skins = array();
		
		// get skins
			$sql = "SELECT id, name FROM ".$db->module('pages_skins');
			if($active) $sql .= " WHERE active = '1'";
			$sql .= " ORDER BY name";
			$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch skins.');
		
		// return skins
			while($row = mysql_fetch_array($res, MYSQL_ASSOC)) $skins[] = $row;
			return $skins;
		
	}
	
	
	/**
	 * Print skins dropdown
	 * 
	 * @param	string		$name
	 * @param	int			$value
	 * @param	bool		$active
	 * @return	void
	 */
	
	public function printSkinsDropdown($name='skins', $value=false, $active=true)
	{
		// required
			global $cosa, $db;
			$skins = $this->getSkins($active);
		
		// check for multiple
			if(empty($skins)) return false;
			if(count($skins) == 1) echo '<input type="hidden" name="'.$name.'" value="'.$skins[0]['id'].'" />'."\n";
			else {
				echo '<select name="'.$name.'">'."\n\t";
				foreach($skins as $k => $skin) {
					$selected = ($value == $skin['id']) ? ' selected="selected"' : '';
					echo '<option value="'.stripslashes($skin['id']).'"'.$selected.'>'.stripslashes($skin['name']).'</option>'."\n\t";
				}
				echo '</select>'."\n";
			}
		
	}
	
	
	/**
	 * Get the number of skins available
	 * 
	 * @param	bool		$active
	 * @return	int
	 */
	
	public function numSkins($active=true)
	{
		return count($this->getSkins($active));
	}
	
	
	
}

?>